package com.qili.controller.sys;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qili.base.controller.BaseController;
import com.qili.base.entity.CurrentUser;
import com.qili.core.annotation.Log;
import com.qili.core.annotation.Log.LOG_TYPE;
import com.qili.core.quartz.JobTask;
import com.qili.core.utils.DictTypes;
import com.qili.entity.base.BaseCompany;
import com.qili.entity.base.BaseDict;
import com.qili.entity.sys.SysRole;
import com.qili.entity.sys.SysRoleUser;
import com.qili.entity.sys.SysUser;
import com.qili.entity.sys.SysUserWorkExperience;
import com.qili.entity.sys.dto.SysUserDTO;
import com.qili.exception.MyException;
import com.qili.service.SysUserService;
import com.qili.service.base.BaseCompanyService;
import com.qili.service.base.BaseDictService;
import com.qili.service.sys.RoleService;
import com.qili.service.sys.RoleUserService;
import com.qili.service.sys.SysUserWorkExperienceService;
import com.qili.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhuxiaomeng
 * @date 2017/12/6.
 * @email 154040976@qq.com
 * 用户管理
 */
//@Api(value="user")
@Slf4j
@Controller
@RequestMapping(value = "/user")
public class UserController extends BaseController {

    //private static final Logger

    @Autowired
    SysUserService userService;

    @Autowired
    RoleUserService roleUserService;

    @Autowired
    JobTask task;

    @Autowired
    BaseDictService baseDictService;

    @Autowired
    RoleService roleService;

    @Autowired
    BaseCompanyService companyService;

    @Autowired
    SysUserWorkExperienceService userWorkExperienceService;
    /**
     * @param
     * @Author:Zhangshuo
     * @Description:
     * @Date:9:38 2020/11/23
     */
    @GetMapping(value = "mainTest")
    @RequiresPermissions("user:show")
    public String showTest() {
        return "system/user/mainTest";
    }

    /**
     * @param model
     * @Author:Zhangshuo
     * @Description:
     * @Date:9:38 2020/11/23
     */
    @GetMapping(value = "showUser")
    @RequiresPermissions("user:show")
    public String showUser(Model model) {
        //获取所有的角色：
        List<SysRole> sysRoles = roleService.selectAll();
        model.addAttribute("roleList",sysRoles);
        return "/system/user/userList";
    }

    /**
     * @param model
     * @param user
     * @param page
     * @param limit
     * @Author:Zhangshuo
     * @Description:
     * @Date:9:38 2020/11/23
     */
    @GetMapping(value = "showUserList")
    @ResponseBody
    @RequiresPermissions("user:show")
    public ReType showUser(Model model, SysUser user, String page, String limit) {
        List<SysUserDTO> tList = null;
        Page<SysUserDTO> tPage = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
        try {
            tList = userService.selectUsefulUsers(user);
            for(SysUserDTO user1:tList){
                if(StringUtils.isNotBlank(user1.getYwType())){
                    userService.selectUserYwTypeName(user1);
                }
            }
        } catch (MyException e) {
            log.error("class:BaseServiceImpl ->method:show->message:" + e.getMessage());
            e.printStackTrace();
        }
        return new ReType(tPage.getTotal(), tList);
    }

    /**
     * @param model
     * @param roleId
     * @param page
     * @param limit
     * @Author:Zhangshuo
     * @Description:
     * @Date:9:36 2020/11/23
     */
    @ApiOperation(value = "/listByRoleId", httpMethod = "GET", notes = "展示角色")
    @GetMapping(value = "listByRoleId")
    @ResponseBody
    @RequiresPermissions("user:show")
    public String showUser(Model model, String roleId, int page, int limit) {
        JSONObject returnValue = new JSONObject();
        Page<Object> startPage = PageHelper.startPage(page, limit);
        List<SysUser> users = userService.getUserByRoleId(roleId);
        returnValue.put("users", users);
        returnValue.put("totals", startPage.getTotal());
        return JSON.toJSONString(returnValue);
    }

    /**
     * @param model
     * @Author:Zhangshuo
     * @Description: 新增用户弹窗
     * @Date:9:36 2020/11/23
     */
    @GetMapping(value = "showAddUser")
    @RequiresPermissions("user:select")
    public String goAddUser(Model model) {
        List<Checkbox> checkboxList = userService.getUserRoleByJson(null);
        //添加业务类型:
        BaseDict select = new BaseDict();
        select.setBadtTypecode(DictTypes.YW_TYPE.getType());
        List<BaseDict> ywTypeList = baseDictService.select(select);
        //供需:
        BaseDict gxSelect = new BaseDict();
        gxSelect.setBadtTypecode(DictTypes.GXLX.getType());
        List<BaseDict> gxTypeList = baseDictService.select(gxSelect);
        //个人/组织
        BaseDict personTypeSelect = new BaseDict();
        personTypeSelect.setBadtTypecode(DictTypes.PERSON_TYPE.getType());
        List<BaseDict> personTypeList = baseDictService.select(personTypeSelect);
        //部门
        BaseDict deptDict = new BaseDict();
        deptDict.setBadtTypecode(DictTypes.DEPT.getType());
        List<BaseDict> deptList = baseDictService.select(deptDict);
        //公司
        Example example = new Example(BaseCompany.class);
        example.setOrderByClause("bc_create_time desc");
        List<BaseCompany> companyList = companyService.selectByExample(example);
        model.addAttribute("companyList", companyList);
        model.addAttribute("deptList", deptList);
        model.addAttribute("boxJson", checkboxList);
        model.addAttribute("ywTypeList", ywTypeList);
        model.addAttribute("gxTypeList", gxTypeList);
        model.addAttribute("personTypeList", personTypeList);
        return "/system/user/add-user";
    }

    /**
     * @param user
     * @param role
     * @Author:Zhangshuo
     * @Description:
     * @Date:9:37 2020/11/23
     */
    @ApiOperation(value = "/addUser", httpMethod = "POST", notes = "添加用户")
    @Log(desc = "添加用户")
    @PostMapping(value = "addUser")
    @ResponseBody
    @RequiresPermissions("user:select")
    public JsonUtil addUser(SysUser user, String[] role) {
        if (user == null) {
            return JsonUtil.error("获取数据失败");
        }
        if (StringUtils.isBlank(user.getUsername())) {
            return JsonUtil.error("用户名不能为空");
        }
        if (StringUtils.isBlank(user.getPassword())) {
            return JsonUtil.error("密码不能为空");
        }
//        if (role == null) {
//            return JsonUtil.error("请选择角色");
//        }
        int result = userService.checkUser(user.getUsername());
        if (result > 0) {
            return JsonUtil.error("用户名已存在");
        }
        if(StringUtils.isNotBlank(user.getPhoneNumber())){
            JsonUtil jsonUtil = userService.checkSameTelephone(user);
            if(!jsonUtil.isFlag()){
                return JsonUtil.error("联系方式已存在");
            }
        }
        //如果输入了邮箱,验证邮箱是否重复:
        if(StringUtils.isNotBlank(user.getEmail())){
            int checkEmailResult = userService.checkUserEmail(user.getEmail());
            if (checkEmailResult > 0) {
                return JsonUtil.error("邮箱已存在");
            }
        }
        JsonUtil j = new JsonUtil();
        try {
            userService.insertSelective(user);
            userService.setUserFilePath(user);
            SysUserWorkExperience nowWork = user.getNowWork();
            if(nowWork!=null){
                if(StringUtils.isNotBlank(nowWork.getSuweId())){
                    userWorkExperienceService.updateByPrimaryKeySelective(user.getNowWork());
                }else{
                    nowWork.setIfNow("1");
                    nowWork.setSuId(user.getId());
                    userWorkExperienceService.insertSelective(nowWork);
                }
            }
            SysRoleUser sysRoleUser = new SysRoleUser();
            sysRoleUser.setUserId(user.getId());
            if(role!=null  && role.length>0){
                for (String r : role) {
                    sysRoleUser.setRoleId(r);
                    roleUserService.insertSelective(sysRoleUser);
                }
            }
            j.setMsg("保存成功");
        } catch (MyException e) {
            j.setMsg("保存失败");
            j.setFlag(false);
            e.printStackTrace();
        }
        return j;
    }

    /**
     * @Author:liuyang
     * @Description:    导入表格中的用户
     * @Date:9:37 2021/02/23
     */
    @ApiOperation(value = "/addUsers", httpMethod = "POST", notes = "添加用户")
    @Log(desc = "通过文件添加用户")
    @PostMapping(value = "addUsers")
    @ResponseBody
    public JsonUtil addUsers(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        if (file == null) {
            return JsonUtil.error("获取数据失败");
        }

        StringBuffer message= new StringBuffer("");

        try {
            message = userService.buldImportSqtj(file,message);
        } catch (Exception e) {
            message=message.append("导入用户信息错误,请联系管理员!<br/>");
        }
        if(StringUtils.isNotBlank(message)){
            return JsonUtil.error(message.toString());
        }else{
            return JsonUtil.sucess("导入成功");
        }
    }

    /**
     * @Author:liuyang
     * @Description:    导入表格中用户的角色
     * @Date:9:37 2021/02/23
     */
    @ApiOperation(value = "/addUserRoles", httpMethod = "POST", notes = "添加角色")
    @Log(desc = "通过文件添加角色")
    @PostMapping(value = "addUserRoles")
    @ResponseBody
    public JsonUtil addUserRoles(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        if (file == null) {
            return JsonUtil.error("获取数据失败");
        }

        StringBuffer message= new StringBuffer("");

        try {
            message = userService.importUserRoles(file,message);
        } catch (Exception e) {
            e.printStackTrace();
            message=message.append("导入用户角色信息错误,请联系管理员!<br/>");
        }
        if(StringUtils.isNotBlank(message)){
            return JsonUtil.error(message.toString());
        }else{
            return JsonUtil.sucess("导入成功");
        }
    }

    /**
     * @param id
     * @param model
     * @param detail
     * @Author:Zhangshuo
     * @Description: 用户编辑弹窗
     * @Date:9:37 2020/11/23
     * 用户查看也是这个方法
     */
    @GetMapping(value = "updateUser")
    @RequiresPermissions(value={"user:update","user:view"},logical= Logical.OR)
    public String goUpdateUser(String id, Model model, boolean detail) {
        if (StringUtils.isNotEmpty(id)) {
            //用户-角色
            List<Checkbox> checkboxList = userService.getUserRoleByJson(id);
            SysUser user = userService.selectByPrimaryKey(id);
            model.addAttribute("user", user);
            model.addAttribute("boxJson", checkboxList);
            if(user != null && StringUtils.isNotBlank(user.getSource()) && "001".equals(user.getSource())){
                //正中的：
                //公司
                Example example = new Example(BaseCompany.class);
                example.setOrderByClause("bc_create_time desc");
                List<BaseCompany> companyList = companyService.selectByExample(example);
                model.addAttribute("companyList", companyList);
                //查询该人员对应的当前工作信息:
                SysUserWorkExperience nowWork = new SysUserWorkExperience();
                nowWork.setSuId(user.getId());
                nowWork.setIfNow("1");
                List<SysUserWorkExperience> select = userWorkExperienceService.select(nowWork);
                if(select!=null && select.size()>0){
                    user.setNowWork(select.get(0));
                }
            }
        }

        //添加业务类型:
        BaseDict select = new BaseDict();
        select.setBadtTypecode(DictTypes.YW_TYPE.getType());
        List<BaseDict> ywTypeList = baseDictService.select(select);
        //供需:
        BaseDict gxSelect = new BaseDict();
        gxSelect.setBadtTypecode(DictTypes.GXLX.getType());
        List<BaseDict> gxTypeList = baseDictService.select(gxSelect);
        //部门
        BaseDict deptDict = new BaseDict();
        deptDict.setBadtTypecode(DictTypes.DEPT.getType());
        List<BaseDict> deptList = baseDictService.select(deptDict);
        //个人/组织
        BaseDict personTypeSelect = new BaseDict();
        personTypeSelect.setBadtTypecode(DictTypes.PERSON_TYPE.getType());
        List<BaseDict> personTypeList = baseDictService.select(personTypeSelect);
        model.addAttribute("detail", detail);
        model.addAttribute("deptList", deptList);
        model.addAttribute("ywTypeList", ywTypeList);
        model.addAttribute("gxTypeList", gxTypeList);
        model.addAttribute("personTypeList", personTypeList);
        return "system/user/update-user";
    }

    /**
     * @param user
     * @param role
     * @Author:Zhangshuo
     * @Description: 编辑用户
     * @Date:9:37 2020/11/23
     */
    @ApiOperation(value = "/updateUser", httpMethod = "POST", notes = "更新用户")
    @Log(desc = "更新用户", type = LOG_TYPE.UPDATE)
    @PostMapping(value = "updateUser")
    @ResponseBody
    @RequiresPermissions("user:update")
    public JsonUtil updateUser(SysUser user, String role[]) {
        JsonUtil jsonUtil = new JsonUtil();
        jsonUtil.setFlag(false);
        if (user == null) {
            jsonUtil.setMsg("获取数据失败");
            return jsonUtil;
        }
        try {
            if(StringUtils.isNotBlank(user.getPhoneNumber())){
                JsonUtil jsonUtil1 = userService.checkSameTelephoneWhenUpdate(user);
                if (!jsonUtil1.isFlag()) {
                    return jsonUtil1;
                }
            }
            if(StringUtils.isNotBlank(user.getEmail())){
                JsonUtil jsonUtil2 = userService.checkSameEmailWhenUpdate(user);
                if (!jsonUtil2.isFlag()) {
                    return jsonUtil2;
                }
            }
            SysUser oldUser = userService.selectByPrimaryKey(user.getId());
            BeanUtil.copyNotNullBean(user, oldUser);
            userService.updateByPrimaryKeySelective(oldUser);
            SysUserWorkExperience nowWork = user.getNowWork();
            if(nowWork!=null){
                userService.updateUserNowWork(user);
            }
            SysRoleUser sysRoleUser = new SysRoleUser();
            sysRoleUser.setUserId(oldUser.getId());
            List<SysRoleUser> keyList = userService.selectByCondition(sysRoleUser);
            for (SysRoleUser sysRoleUser1 : keyList) {
                roleUserService.deleteByPrimaryKey(sysRoleUser1);
            }
            if (role != null) {
                for (String r : role) {
                    sysRoleUser.setRoleId(r);
                    roleUserService.insert(sysRoleUser);
                }
            }
            jsonUtil.setFlag(true);
            jsonUtil.setMsg("修改成功");
            userService.updateCurrent(user);
        } catch (MyException e) {
            e.printStackTrace();
        }
        return jsonUtil;
    }

    /**
     * @param id
     * @param flag
     * @Author:Zhangshuo
     * @Description: 删除用户
     * @Date:9:37 2020/11/23
     */
    @Log(desc = "删除用户", type = LOG_TYPE.DEL)
    @ApiOperation(value = "/del", httpMethod = "POST", notes = "删除用户")
    @PostMapping(value = "/del")
    @ResponseBody
    @RequiresPermissions("user:del")
    public JsonUtil del(String id, boolean flag) {
        return userService.delById(id, flag);
    }

    /**
     * @param id
     * @param model
     * @Author:Zhangshuo
     * @Description:
     * @Date:9:37 2020/11/23
     */
    @GetMapping(value = "goRePass")
    @RequiresPermissions("user:repass")
    public String goRePass(String id, Model model) {
        if (StringUtils.isEmpty(id)) {
            return "获取账户信息失败";
        }
        SysUser user = userService.selectByPrimaryKey(id);
        model.addAttribute("user", user);
        return "/system/user/re-pass";
    }

    /**
     * 修改密码
     *
     * @param id
     * @return
     */
    @Log(desc = "重置密码", type = LOG_TYPE.UPDATE)
    @PostMapping(value = "rePass")
    @ResponseBody
    @RequiresPermissions("user:repass")
    public JsonUtil rePass(String id) {
        boolean flag = StringUtils.isEmpty(id) ;
        JsonUtil j = new JsonUtil();
        j.setFlag(false);
        if (flag) {
            j.setMsg("获取数据失败，修改失败");
            return j;
        }
        SysUser user = userService.selectByPrimaryKey(id);
        String  newPwd = Md5Util.getMD5("12345678", user.getUsername());
//        pass = Md5Util.getMD5(pass, user.getUsername());
//        if (!pass.equals(user.getPassword())) {
//            j.setMsg("密码不正确");
//            return j;
//        }
        if (newPwd.equals(user.getPassword())) {
            j.setMsg("新密码不能与旧密码相同");
            return j;
        }
        user.setPassword(newPwd);
        try {
            userService.rePass(user);
            j.setMsg("修改成功");
            j.setFlag(true);
        } catch (MyException e) {
            e.printStackTrace();
        }
        return j;
    }

    @Autowired
    UploadUtil uploadUtil;

    /**
     * @param req
     * @param file
     * @param model
     * @Author:Zhangshuo
     * @Description:头像上传 目前首先相对路径
     * @Date:9:41 2020/11/23
     */
    @PostMapping(value = "upload")
    @ResponseBody
    public JsonUtil imgUpload(HttpServletRequest req, @RequestParam("file") MultipartFile file, ModelMap model) throws IOException {
        LoadType loadType = uploadUtil.upload(file, UploadType.NONE);
        JsonUtil j = new JsonUtil();
        j.setMsg(loadType.getFileName());
        return j;
    }

    /**
     * @param uname
     * @param req
     * @Author:Zhangshuo
     * @Description:验证用户名是否存在
     * @Date:9:41 2020/11/23
     */
    @GetMapping(value = "checkUser")
    @ResponseBody
    public JsonUtil checkUser(String uname, HttpServletRequest req) {
        JsonUtil j = new JsonUtil();
        j.setFlag(Boolean.FALSE);
        if (StringUtils.isEmpty(uname)) {
            j.setMsg("获取数据失败");
            return j;
        }
        int result = userService.checkUser(uname);
        if (result > 0) {
            j.setMsg("用户名已存在");
            return j;
        }
        j.setFlag(true);
        return j;
    }

    /**
     * @param user
     * @Author:Zhangshuo
     * @Description:
     * @Date:9:39 2020/11/23
     */
    @ResponseBody
    @GetMapping(value = "getdicts")
    public ReType getUsersDicts(SysUserDTO user) {
        ReType re = new ReType();
        try {
            List<SysUser> AlstUsers = userService.getUserDicts(user);
            re.setCode(200);
            re.setData(AlstUsers);
        } catch (Exception e) {
            e.printStackTrace();
            re.setCode(1);
            re.setMsg("获取用户字典异常！！" + e.getMessage());
        }
        return re;
    }

    /**
     * @param pTagId
     * @Description:
     * @Author:Zhangshuo
     * @Date:9:39 2020/11/23
     */
    @ResponseBody
    @GetMapping(value = "newtag")
    public JsonUtil newTags(String pTagId, String pTagName) {
        try {
            CurrentUser currentUser = CommonUtil.getUser();
            String AsNumTags = currentUser.getNumTag();
            if(StringUtil.isBlank(AsNumTags)){
                String userId=CommonUtil.getUserId();
                SysUser  sysUser=userService.selectByPrimaryKey(userId);
                String tagnum=sysUser.getNumTag();
                if(StringUtil.isBlank(tagnum)){
                    return JsonUtil.error("操作失败。请在个人中心设置项目显示标签个数");
                }else{
                    AsNumTags=tagnum;
                }
            }
            Integer AiNumTag = Integer.valueOf(AsNumTags);
            String AsTags = currentUser.getTags();
            String[] AyTags;
            if (StringUtil.isBlank(AsTags)) {
                AsTags = "";
                AyTags = new String[1];
                AyTags[0] = pTagId + ":" + pTagName;
                AsTags = StringUtils.join(AyTags, ";") + ";";
            } else {
                AyTags = AsTags.split(";");
                if (AyTags.length < AiNumTag) {
                    AiNumTag = AyTags.length+1;
                }
                //创建新的数组
                String[] targetnew = new String[AiNumTag];
                /*原数组中元素复制到新数组中*/
                for (int i = 0;i < AyTags.length;i++){
                    //数组的长度不能大于设置的标签数量
                    if(i<AiNumTag){
                        targetnew[i] = AyTags[i];
                    }

                }
                /*新数组中元素依次向后位移*/
                for (int i = AiNumTag - 1; i > 0; i--) {
                    if (StringUtil.isNotBlank(targetnew[i-1])) {
                        targetnew[i] = targetnew[i-1];
                        targetnew[i-1]="";
                    }
                }
                targetnew[0]= pTagId + ":" + pTagName;
                AsTags=StringUtils.join(targetnew, ";") + ";";
            }
            SysUser sysUser = new SysUser();
            sysUser.setId(currentUser.getId());
            sysUser.setTags(AsTags);
            userService.updateTags(sysUser);
            currentUser.setTags(AsTags);
            Session session = com.qili.core.shiro.Principal.getSession();
            session.setAttribute("currentPrincipal", currentUser);
            return JsonUtil.sucess("操作成功。");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.error("操作失败。" + e.getMessage());
        }
    }

    /**
     * @param pTagId
     * @Description:
     * @Author:Zhangshuo
     * @Date:9:39 2020/11/23
     */
    @ResponseBody
    @GetMapping(value = "deltag")
    public JsonUtil delTags(String pTagId) {
        try {
            CurrentUser currentUser = CommonUtil.getUser();
            String AsTags = currentUser.getTags();
            String[] AyTags = AsTags.split(";");
            Integer AiCnt = AyTags.length;
            ArrayList<String> objArray = new ArrayList<String>();
            for (int i = 0; i < AiCnt; i++) {
                String AsTmp = AyTags[i];
                if (StringUtil.isNotBlank(AsTmp)) {
                    String[] AyTmp = AsTmp.split(":");
                    if (!AyTmp[0].equals(pTagId)) {
                        objArray.add(AsTmp);
                    }
                }
            }
            if(objArray.size()>0){
                AsTags = String.join(";", objArray) + ";";
            }else{
                AsTags="";
            }
            SysUser sysUser = new SysUser();
            sysUser.setId(currentUser.getId());
            sysUser.setTags(AsTags);
            userService.updateTags(sysUser);
            currentUser.setTags(AsTags);
            Session session = com.qili.core.shiro.Principal.getSession();
            session.setAttribute("currentPrincipal", currentUser);
            return JsonUtil.sucess("操作成功。");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.error("操作失败。" + e.getMessage());
        }
    }

    //查询用户供需的类型
    @RequestMapping(value = "selectGxtype")
    @ResponseBody
    public JsonUtil selectGxtype(){
        JsonUtil js=new JsonUtil();
        String userId=CommonUtil.getUserId();
        SysUser user=userService.selectUserById(userId);
        if(user!=null&&!"".equals(user)){
            if (StringUtils.isNotBlank(user.getGxType())){
                js.setFlag(true);
            }else{
                js.setFlag(false);
            }
        }
        return js;
    }

    //更新用户供需的类型
    @RequestMapping(value = "insertGxtype")
    @ResponseBody
    public JsonUtil insertGxtype(String type){
        JsonUtil js=new JsonUtil();
        SysUser user=new SysUser();
        user.setId(CommonUtil.getUserId());
        user.setGxType(type);
        if(userService.updateByPrimaryKeySelective(user)>0){
            js.setFlag(true);
        }else {
            js.setFlag(false);
        }
        return js;
    }

}
